//
// Created by 刘平 on 2018/12/22.
//

#pragma once

#include <thread>
#include <vector>
#include <atomic>
#include <functional>

using TaskHandler = std::function<void ()>;
class ThreadGroup {
 private:
    std::atomic<bool> is_stop;
    std::vector<std::thread> threads;

 public:
    ThreadGroup(const ThreadGroup&) = delete;
    ThreadGroup &operator=(const ThreadGroup &) = delete;

    ThreadGroup() {
        is_stop.store(false);
    }
    void StopAll() {
        is_stop.store(true);
        for (auto &t : threads) {
            t.join();
        }
    }

    void AddTaskTick(TaskHandler && task) {
        threads.push_back(std::thread(std::bind(&ThreadGroup::TickTask, this, std::move(task))));
    }

 private:
    void TickTask(TaskHandler task) {
        while (!is_stop) {
            task();
        }
        task(); // 可能最后在处理任务和设置is_stop之间有消息产生 所以还需要调用一次
    }
};
